//
//  HMPublishViewController.swift
//  WeiBo
//
//  Created by apple on 16/6/30.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

let holderString = "听说下雨天吃烤鸡翅很配哦"

class HMPublishViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        
        setupTextView()
        
        setupToolBar()
        
        // 监听键盘的通知
        // UIKeyboardDidChangeFrameNotification -- 已经改变
        // UIKeyboardWillChangeFrameNotification -- 将要改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeNotification:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "insertEmoticon:", name: kNoitficationTransformEmoticon, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteEmoticon:", name: kNotificationDeleteEmotiocn, object: nil)
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        // 注销第一响应者
        textView.resignFirstResponder()
        
        
    }
    
    //MARK:-- 设置导航栏
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "publish")
        
        
        // 导航titlt
//        title = "发布微博\n itheima"
        let label = UILabel(frame: CGRectMake(0, 0, 200, 44))
        
//        label.text = "发布微博\n itheima"
        
        label.numberOfLines = 0
        
        label.textAlignment = .Center
        
        let str = "发布微博\n itheima"
        
        // 创建一个 NSAttributedString 对象, 他是不可变的,所以我们给他添加属性的时候不可以
        // 可以设置他的属性
        //
        let attribute = NSAttributedString(string: str)
        
        // 定义一个可变的 AttributeStirng
        let muAttribute = NSMutableAttributedString(string: str)
        
        // 添加属性
        // 把 NSFontAttributeName 记住一个就可以了,点击他能够找到所有的
        //
        muAttribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(16),NSForegroundColorAttributeName: UIColor.yellowColor()], range: NSMakeRange(0, 4))
        
        // 再去设置 itheima
        muAttribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14),NSBackgroundColorAttributeName: UIColor.redColor()], range: NSMakeRange(6, str.characters.count - 6))
        
        
        label.attributedText = muAttribute
        
        navigationItem.titleView = label
        
    }

    @objc private func dismiss(){
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    @objc private func publish(){
        
       // 判断有没有图片
        if chooseView.getImages().count > 0 {
            upload()
        } else {
            
            update()
        }
        
    }
    
    // 上传文字
    private func update (){
        
        
        printLog(textView.attributedText)
        // 发布微博
        
        /*
        access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
        status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
        */
        
        guard let access_token = HMOauthViewModel.shareInstance.access_token else {
            return
        }
        let params = ["access_token":access_token,
            "status":textView.getPublishTextString(),
            //"visible":NSNumber(integer: 1)
        ]
        // 打印一下请求参数
        printLog(params)
        
        HMHTTPClient.request(.POST, URLString: "https://api.weibo.com/2/statuses/update.json", parameters: params, success: { (JSON) -> Void in
            printLog(JSON)
            SVProgressHUD.showInfoWithStatus("发布成功")
            
            }) { (error) -> Void in
                printLog(error)
                SVProgressHUD.showErrorWithStatus(error.description)
        }
        
        
        
    }
    // 上传图片
    private func upload(){
        
//        https://upload.api.weibo.com/2/statuses/upload.json
     
        /*
        access_token 	false 	string 	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
        status 	true 	string 	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
        
        
        pic 要放在form表单里
        pic 	true 	binary 	要上传的图片，仅支持JPEG、GIF、PNG格式，图片大小小于5M。
        */
        
        guard let access_token = HMOauthViewModel.shareInstance.access_token else {
            return
        }
        
        // 拼接参数
        let params = ["access_token":access_token,
                        "status":textView.getPublishTextString()
        ]
        
        
        // 有些公司,上传图片不用 表单;
        // 他把二进制图片 base64编码,把编码后的字符串以参数的形式,POST过去
        
        
        // 获取图片的二进制
        // 因为是测试,所以进行了一下强制解包
        let image = chooseView.getImages().first!
        
        // 需要把image 转换成NSData
        // 压缩的质量  0~1 -- 压缩的质量并没有很严格意义上的界限,我们可以和后台多次测试这个压缩值,
        let data = UIImageJPEGRepresentation(image, 0.3)
        
        HMHTTPClient.shareInstance.POST("https://upload.api.weibo.com/2/statuses/upload.json", parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
            
            /*
                第一个参数: 我们要上传的二进制. 这里是 图片的二进制
                第二个参数: 接口文档归档的 字段名字
                第三个参数: 文件名字,文件名字随意
                第四个参数: mineType
            */
            
            // 如果要一次性上传多张图片,可以 for 循环这个方法
            formdata.appendPartWithFileData(data!, name: "pic", fileName: "aa.png", mimeType: "image/jpeg")
            
            }, progress: nil, success: { (_ , JSON) -> Void in
                printLog(JSON)
                SVProgressHUD.showInfoWithStatus("发布成功")
            }) { (_ , error) -> Void in
                SVProgressHUD.showErrorWithStatus(error.description)
        }
        
    }
    
    //MARK:-- 设置TextV iew
    private func setupTextView(){
        
        // textView的占位符 有 2种实现方式
        // 1. label
        // 2. 重绘
        
        view.addSubview(textView)
        
        // 设置大小 = view.bounds
        textView.frame = view.bounds
        
        // 设置font ,不设置会崩溃
        textView.font = UIFont.systemFontOfSize(16)
        
        // 设置占位符
        textView.holderString = holderString
        
        // 问题: 1.占位符没有消失 --  2. 占位符位置不对 -- 修改CGPoint
        
        // 有文字的时候,占位符消失; 什么时候有文字; 监听
        textView.delegate = self
        
        // textView和键盘相关的 keyboard
        textView.keyboardDismissMode = .OnDrag
        // 一定要设置alwaysBounceVertical 是垂直
        textView.alwaysBounceVertical = true
        
        
        //MARK:-- 添加collectionView
        
        textView.addSubview(chooseView)
        
        chooseView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textView.snp_left).offset(HomeCellMargin)
            make.top.equalTo(textView.snp_top).offset(100)
            make.width.height.equalTo(kUIScreenWidth - 2 * HomeCellMargin)
        }
    }
    
    //MARK:-- 设置UIToolBar
    private func setupToolBar(){
        
        view.addSubview(toolBar)
        
        toolBar.backgroundColor = UIColor.darkGrayColor()
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
        }
        
        // 我们可以把一些固定的东西按照数据源的形式,展示
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        
        // 初始化一个数组
        var items = [UIBarButtonItem]()
        
        // 对item 进行遍历
        for itemSetting in itemSettings{
            
            
            
            // 设置图片
            let imageName = itemSetting["imageName"]
            
            // 设置按钮的点击方法
            let action = itemSetting["action"]
            
            let button = UIButton(imageName: imageName!, action: action, target: self)
            
            let item = UIBarButtonItem(customView: button)
            
            // 把item添加到数组里
            items.append(item)
            
            // 添加一个弹簧进行间隔
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        // 我们在循环外减少一个弹簧
        items.removeLast()
        
        toolBar.items = items
        
    }
    
    //MARK:-- 控制器的 deinit
    deinit {
        
        // 移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
        printLog("88")
    }
    
    //MARK:-- 懒加载
    private lazy var textView: HMHolderTextView = HMHolderTextView()
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var chooseView: HMChooseView = {
    
        let choose = HMChooseView()
        
        // 闭包 -> HMPublishController -> ChooseView -> 闭包
        // 闭包里破除循环引用有三种形式 
        // [weak self] -- weak
        // [unowned self] -- asign
        weak var weakSelf = self
        choose.closure = { [weak self] ()->() in
        
//            printLog("点击回调")
//            self.choosePicture()
//            self?.choosePicture()
            weakSelf?.choosePicture()
        }
        
        return choose
        
    }()
    
    
    //键盘视图
    private lazy var emoticonView: HMEmoticonView = {
    
        let emoticon = HMEmoticonView(frame: CGRectMake(0,0,kUIScreenWidth,216))
        
        return emoticon
    }()
}

//MARK:-- 控制器的通知方法
extension HMPublishViewController{
    
    @objc private func changeNotification(noti:NSNotification){
        
        printLog(noti.userInfo)
        
        /*
            键盘弹出来的时候的通知信息
        
        [UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 667}, {375, 258}}, UIKeyboardCenterEndUserInfoKey: NSPoint: {187.5, 538}, UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {375, 258}}, 
        
            UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 409}, {375, 258}}, UIKeyboardAnimationDurationUserInfoKey: 0.25,
        
            UIKeyboardCenterBeginUserInfoKey: NSPoint: {187.5, 796}, UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1]
        */
        /*
        键盘返回的通知信息
        
        [UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 409}, {375, 258}}, UIKeyboardCenterEndUserInfoKey: NSPoint: {187.5, 796}, UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {375, 258}}, UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 667}, {375, 258}}, UIKeyboardAnimationDurationUserInfoKey: 0.25, UIKeyboardCenterBeginUserInfoKey: NSPoint: {187.5, 538}, UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1]
        */
        
        
        /*键盘弹出来的时候的通知信息
        
        UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 409}, {375, 258}}, UIKeyboardAnimationDurationUserInfoKey: 0.25,
        */
        
       
        
        /*键盘返回的通知信息
        UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 667}, {375, 258}}, UIKeyboardAnimationDurationUserInfoKey: 0.25,
        */
        
        // CGRectValue 同学知道就可以了,我们可以通过这样的方法,拿到里边是 NSRect 的值
        let rect = noti.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // 
        if rect.origin.y == KUIScreenHeight {
            
            // toolbar 就在底部
            // 距离底部的 offset = 0
            toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(view.snp_bottom).offset(0)
            })
            
        } else {
            
            // toolbar 距离底部的 offset = 键盘的高度
            toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(view.snp_bottom).offset(-rect.size.height)
            })
        }
        
        
        // 添加一个约束动画
        UIView.animateWithDuration(0.25) { () -> Void in
            // 欢迎界面的时候,我们提到过约束动画要调用layoutIfNeeded
            self.toolBar.layoutIfNeeded()
            
        }
    }
    
    @objc private func insertEmoticon(noti: NSNotification){
    
        // 关于可选项最聪明的做法,就是系统提示
        // 然后自己再去思考
        
        // 可选项 要么有值,要么没值
        if let userInfo = noti.userInfo {
            
            // userInfo 是一个字典,emoticon 会由于字典里key值的改变而 有可能有值,有可能没有值
            
            // let emoticon: AnyObject?
            // emoticon实际类型是 HMEmoticon 
            // 需要把 AnyObject? 类型转换成 HMEmtocion
            
            /*
                默认 as 就是  String 转 NSString ,swift数组 转 NSArray
                可选?
                强!
                as? 和 as! 的选择标准是 看前边的返回类型
            */
            let emoticon = userInfo["emoticon"] as? HMEmoticon
            
            if let Oemoticon = emoticon {
                
                textView.insertEmoticon(Oemoticon)
                
            }
        }
        
        
    }
    
    @objc private func deleteEmoticon(noti: NSNotification){
        
        textView.deleteBackward()
    }
    
}

// MARK:-- 底部视图的按钮点击方法
extension HMPublishViewController{
    
///  选择图片
    @objc private func choosePicture(){
        
        // 防止多余9张图片
        if chooseView.isPresent() {
            return
        }
        
        
        // 一定要判断一下,能不能访问
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            
            let imagePicker = UIImagePickerController()
            
            /*
            case PhotoLibrary -- 默认类型
            case Camera
            case SavedPhotosAlbum
            */
            // 指定类型
            imagePicker.sourceType = .PhotoLibrary
            
            // 选择图片的话,要设置代理
            imagePicker.delegate = self
            
            // 跳转到指定视图
            presentViewController(imagePicker, animated: true, completion: { () -> Void in
                
            })
        }
        
        
        
        
    }
///  表情键盘
    @objc private func inputEmoticon(){
        
        // inputView 是自定义View的,我们可以试一试
        // 显示表情视图的时候,让 inputView = emoticonView
//        textView.inputView = emoticonView
        
        // 显示键盘的时候,怎么办??? intputView = nil
       
        // 如何切换表情键盘以及键盘,就让 intputView = emoticonView 和 intputVIew = nil来回切换即可
        textView.inputView == nil ? (textView.inputView = emoticonView):(textView.inputView = nil)
        // 调用一下 inputView 其作用的方法
        textView.reloadInputViews()
        
        // 让textView变成第一响应者,弹出对应表情或者键盘
        textView.becomeFirstResponder()
        
        printLog(textView.inputView)
    }
    
}

//MARK:-- 图片选择代理方法
extension HMPublishViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    // 还有一个被移除的方法
    // 还是可以使用的,为什么愿意用这个方法呢? 因为参数有一个image
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        // 需要把 iamge 添加到 ChooseView
        chooseView.addImage(image)
        
        picker.dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    
    // 当我们实现了协议方法之后,需要手动让控制器消失
    
//   // 选择完成图片之后,走的代理方法
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
//        
//        picker.dismissViewControllerAnimated(true) { () -> Void in
//            
//        }
//        
//    }
    // 点击cancel的时候,走这个方法
    func imagePickerControllerDidCancel(picker: UIImagePickerController){
        
        picker.dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
}

//MARK:-- UITextView的代理方法
extension HMPublishViewController: UITextViewDelegate {
    
//    func textViewDidBeginEditing(textView: UITextView) {
//        
//        self.textView.holderString = ""
//        // 是由于我们重绘导致的
//        self.textView.setNeedsDisplay()
//        
//    }
    
    func textViewDidChange(textView: UITextView) {
        
        if self.textView.hasText(){
            
            self.textView.holderString = ""
            
        } else {
            
            self.textView.holderString = holderString
        }
        
        self.textView.setNeedsDisplay()
        
    }
    
}
